﻿using CNFM_CROCODILE_LOGO.Core.Domain.Entity;
using CNFM_CROCODILE_LOGO.OAuth.OAuth;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace CNFM_CROCODILE_LOGO.AOP.OAuth
{
    public static class JwtHelp
    {

        public static string JwtToekn(CrocodileUser model, string role = null, string enpid = null)
        {
            string token = string.Empty;

            //每次登陆动态刷新
            Const.ValidAudience = model.LoginName + model.Password + DateTime.Now.ToString();
            // push the user’s name into a claim, so we can identify the user later on.
            //这里可以随意加入自定义的参数，key可以自己随便起
            var claims = new[]
            {
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                    new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddDays(30)).ToUnixTimeSeconds()}"),
                     new Claim(ClaimTypes.PrimarySid, model.Id,"Id"),
                    new Claim(ClaimTypes.Name, model.UserName,"Name"),
                    new Claim(ClaimTypes.Role, role,"RoleName"),
                    new Claim(ClaimTypes.Country,model.UnCode,"UnCode"),
                    new Claim(ClaimTypes.AuthenticationInstant, string.IsNullOrEmpty(model.EnterpriseId)?"0":model.EnterpriseId, "EnterpriseId")
                };
            //sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
            var Jwttoken = new JwtSecurityToken(
                //颁发者
                issuer: Const.Domain,
                //接收者
                audience: Const.ValidAudience,
                //过期时间
                expires: DateTime.Now.AddDays(30),
                //签名证书
                signingCredentials: creds,
                //自定义参数
                claims: claims
                );

            token = new JwtSecurityTokenHandler().WriteToken(Jwttoken);

            return token;
        }
    }
}
